package function;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import entity.BorrowBook;
import interfaces.BorrowBookDao;

import java.sql.Connection;
import java.util.List;

public class BorrowBookDaoImpl extends BaseDao<BorrowBook> implements BorrowBookDao {


    private static BorrowBookDaoImpl borrowBook = null;

    public BorrowBookDaoImpl() {
    }

    public static BorrowBookDaoImpl getBorrowBook() {
        if (borrowBook == null) {
            borrowBook = new BorrowBookDaoImpl();
        }
        return borrowBook;
    }

    @Override
    public void borrowBooks(Connection connection, BorrowBook borrowBook) {
        String sql = " INSERT INTO `borrow_book`(`reader_id`,`ISBN`,`borrow_date`,`fine`)VALUE(?,?,?,?);";
        try {
            update(connection,sql, borrowBook.getReaderid(), borrowBook.getISBN(), borrowBook.getBorrowdate(), borrowBook.getFine());
            System.out.println("借书成功");
        } catch (MySQLIntegrityConstraintViolationException throwables) {
            System.out.println("暂无该读者或暂无该图书，选择错误，重新输入");
        }


    }

    @Override
    public void returnBooks(Connection connection, BorrowBook borrowBook) {
        String sql="UPDATE borrow_book SET return_date=? WHERE reader_id=? AND ISBN=?";
        try {
            update(connection,sql,borrowBook.getReturndate(),borrowBook.getReaderid(),borrowBook.getISBN());
        } catch (MySQLIntegrityConstraintViolationException throwables) {
            System.out.println("你输入的读者与图书不符合，重新输入");
        }
    }
    public static void returnFine(Connection connection, BorrowBook borrowBook) {
        String sql="UPDATE borrow_book SET fine=? WHERE reader_id=? AND ISBN=?";
        try {
            update(connection,sql,borrowBook.getFine(),borrowBook.getReaderid(),borrowBook.getISBN());
        } catch (MySQLIntegrityConstraintViolationException throwables) {
            throwables.fillInStackTrace();
        }
    }
    @Override
    public List<BorrowBook> getAll(Connection coon) {
        String sql = "SELECT bb.reader_id readerid,bb.ISBN,bb.borrow_date borrowdate,bb.return_date returndate,bb.fine FROM borrow_book bb";
        List<BorrowBook> list = getForList(coon, sql);
        return list;
    }

    public  int timeDifference(Connection coon, BorrowBook borrowBook){

        String sql="SELECT DATEDIFF(`return_date`,b.`borrow_date`)FROM `borrow_book` b WHERE  `reader_id`=? AND `ISBN`=? ";
        int day =(int) getValue(coon, sql, borrowBook.getReaderid(), borrowBook.getISBN());

        return day;



    }



}
